package com.weixing.mall.provider.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.IdGenTagEnum;
import com.weixing.mall.base.enums.SnCodeEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.provider.api.erp.entity.InDepot;
import com.weixing.mall.provider.api.erp.entity.InDepotSub;
import com.weixing.mall.provider.api.erp.entity.OutDepot;
import com.weixing.mall.provider.api.erp.entity.OutDepotSub;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.model.vo.dto.BillProductDto;
import com.weixing.mall.provider.api.model.vo.dto.BillSaveDto;
import com.weixing.mall.provider.api.service.*;
import com.weixing.mall.provider.mapper.DepotMapper;
import com.weixing.mall.provider.mapper.GoodsTransBillMapper;
import com.weixing.mall.provider.mapper.GoodsTransBillProductMapper;
import com.weixing.mall.provider.mapper.ProductStockMapper;
import com.weixing.mall.provider.model.domain.*;
import com.weixing.mall.provider.model.dto.*;
import com.weixing.mall.provider.model.enums.CreateTypeEnum;
import com.weixing.mall.provider.model.enums.DepotTypeEunm;
import com.weixing.mall.provider.model.enums.TransStatusEunm;
import com.weixing.mall.provider.model.query.GoodsTransBillQuery;
import com.weixing.mall.provider.model.query.GoodsTransQuery;
import com.weixing.mall.provider.model.query.ProductStockExistQuery;
import com.weixing.mall.provider.model.vo.DepotVo;
import com.weixing.mall.provider.model.vo.GoodsTransBillListVo;
import com.weixing.mall.provider.model.vo.GoodsTransBillProductVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.DepotUtil;
import com.weixing.mall.util.ListUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsTransBillServiceImpl
 * @Description TODO <br/>
 * @Author gjq
 * @Modified By:
 * @Date 2019/10/28
 * @Version 1.0
 **/

/**
 * <p>
 * 仓库模块-商品调拨单 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-15
 */
@Service
public class GoodsTransBillServiceImpl extends ServiceImpl<GoodsTransBillMapper, GoodsTransBill> implements IGoodsTransBillService {

    @Autowired
    private GoodsTransBillProductMapper goodsTransBillProductMapper;
    @Autowired
    private IGoodsTransBillProductService goodsTransBillProductService;
    @Autowired
    private OrderServiceRpc orderServiceRpc;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private DepotMapper depotMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private IInDepotBillService inDepotBillService;
    @Autowired
    private IOutDepotBillService outDepotBillService;
    @Autowired
    private GoodsTransBillServiceRpc goodsTransBillServiceRpc;
    @Autowired
    private IDepotService depotService;
    @Autowired
    private IGoodsTransBillOperationService goodsTransBillOperationService;
    @Autowired
    private ErpFeign erpFeign;
    @Autowired
    private IProductStockDetailsService productStockDetailsService;

    @Override
    public IPage<GoodsTransBillListVo> selectListOfPage(Page page, GoodsTransBillQuery goodsTransBillQuery, Long uid) {
        List<DepotVo> depotVos = depotMapper.listBySysId(uid, null);
        if (null == depotVos || depotVos.size() == 0) {
            return null;
        }
        List<Long> courseIds = depotVos.stream().map(DepotVo::getId).collect(Collectors.toList());
        return baseMapper.selectListOfPage(page, goodsTransBillQuery, courseIds);
    }

    @Override
    public long create(GoodsTransBillDto goodsTransBillDto, Long uid) {

        //
        GoodsTransBill goodsTransBill = new GoodsTransBill();
        BeanUtils.copyProperties(goodsTransBillDto, goodsTransBill);
        //该方法用于新建流程，所以全部为申请
        goodsTransBill.setTransStatus(TransStatusEunm.TYPE_1.getValue());
        //手动新建类型
        goodsTransBill.setCreateType(CreateTypeEnum.MANUALLY.getValue());
    /*    if (null != goodsTransBillDto.getTransStatus()) {
            goodsTransBill.setTransStatus(goodsTransBillDto.getTransStatus().getValue());
        }*/
        if (null == goodsTransBillDto.getId()) {
            //添加
            //发起人 默认为当前登陆人
            goodsTransBill.setPromoter(uid);
            goodsTransBill.setCreatedBy(uid);
            //计算调货单总数量
            int quantityTotal = 0;
            if (goodsTransBillDto.getProducts().size() > 0) {
                //调货单单相关连商品list
                //二期每一条记录只能有一条记录，进行优化
                /*List<GoodsTransBillProductDto> list = goodsTransBillDto.getProducts();
                for (int i = 0; i < list.size(); i++) {
                    GoodsTransBillProductDto goodsTransBillProductDto = list.get(i);
                    quantityTotal += goodsTransBillProductDto.getQuantity();
                }*/
                goodsTransBill.setQuantity(goodsTransBillDto.getProducts().size());
                double amount=goodsTransBillDto.getProducts() .stream().collect(Collectors.summingDouble(GoodsTransBillProductDto::getDiscountPrice));
                goodsTransBill.setAmount(new BigDecimal(amount).setScale(BigDecimal.ROUND_UP));
            }

            //保存调货单
            save(goodsTransBill);
            long goodsTransId = goodsTransBill.getId();
            if (goodsTransBillDto.getProducts().size() > 0) {
                //调货单单相关连商品list
                List<GoodsTransBillProductDto> list = goodsTransBillDto.getProducts();
                for (int i = 0; i < list.size(); i++) {
                    GoodsTransBillProductDto goodsTransBillProductDto = list.get(i);
                    GoodsTransBillProduct goodsTransBillProduct = new GoodsTransBillProduct();
                    BeanUtils.copyProperties(goodsTransBillProductDto, goodsTransBillProduct);
                    if (ObjectUtil.isNotEmpty(goodsTransBillProductDto.getDiscountPrice())) {
                        goodsTransBillProduct.setDiscountPrice(new BigDecimal(goodsTransBillProductDto.getDiscountPrice()));
                    }
                    try{
                        ItemVo itemVo=itemFeign.findById(goodsTransBillProductDto.getGoodsId()).getData();
                        goodsTransBillProduct.setFl(itemVo.getCatName());
                    }catch (Exception e){

                    }
                    ProductStockDetails details=productStockDetailsService.getById(goodsTransBillProductDto.getId());
                    goodsTransBillProduct.setStockId(goodsTransBillProductDto.getId());
                    goodsTransBillProduct.setCreatedBy(uid);
                    goodsTransBillProduct.setStorehouse(details.getStorehouse());
                    goodsTransBillProduct.setStockSn(details.getStockSn());
                    //添加调拨单id
                    goodsTransBillProduct.setGoodsTransId(goodsTransId);
                    //保存关联商品
                    goodsTransBillProductMapper.insert(goodsTransBillProduct);
                }
            }
            insertOpertaion(goodsTransBill, "新增调拨单");
        } else {
            goodsTransBill.setUpdatedBy(uid);
            goodsTransBill.setUpdatedTime(new Date());
            //计算调货单总数量
            int quantityTotal = 0;
            if (goodsTransBillDto.getProducts().size() > 0) {
                //调货单单相关连商品list
               /* List<GoodsTransBillProductDto> list = goodsTransBillDto.getProducts();
                for (int i = 0; i < list.size(); i++) {
                    GoodsTransBillProductDto goodsTransBillProductDto = list.get(i);
                    quantityTotal += goodsTransBillProductDto.getQuantity();
                }*/
                goodsTransBill.setQuantity(goodsTransBillDto.getProducts().size());
            }
            //修改调拨单
            updateById(goodsTransBill);
            if (goodsTransBillDto.getProducts().size() > 0) {
                //调拨单相关连商品list
                //先删除
                goodsTransBillProductMapper.delete(new QueryWrapper<GoodsTransBillProduct>().eq("goods_trans_id", goodsTransBill.getId()));
                List<GoodsTransBillProductDto> list = goodsTransBillDto.getProducts();
                for (int i = 0; i < list.size(); i++) {
                    GoodsTransBillProductDto goodsTransBillProductDto = list.get(i);
                    GoodsTransBillProduct goodsTransBillProduct = new GoodsTransBillProduct();
                    BeanUtils.copyProperties(goodsTransBillProductDto, goodsTransBillProduct);
                    goodsTransBillProduct.setUpdatedBy(uid);
                    goodsTransBillProduct.setUpdatedTime(new Date());
                    //修改关联商品
                    goodsTransBillProductMapper.insert(goodsTransBillProduct);
                }
            }
            goodsTransBill.setCreatedBy(uid);
            insertOpertaion(goodsTransBill, "修改调拨单");
        }
        return goodsTransBill.getId();
    }

    @Override
    public boolean updateGoodsInfo(NewGoodsTransBillDto gtbd, Long uid) {
        //调货单商品表ID  调货单表ID 数量
        //查出调货单
        GoodsTransBill gtb = getOne(new QueryWrapper<GoodsTransBill>().eq("id", gtbd.getGoodsTransBillId()));
        if (ObjectUtil.isEmpty(gtb)) {
            return false;
        }
        gtb.setUpdatedBy(uid);
        gtb.setUpdatedTime(new Date());
        //更新修改调货单商品数量
        GoodsTransBillProduct gtbp = new GoodsTransBillProduct();
        gtbp.setId(gtbd.getGoodsTransBillProductId());
        gtbp.setQuantity(gtbd.getQuantity());
        gtbp.setUpdatedBy(uid);
        gtbp.setUpdatedTime(new Date());
        goodsTransBillProductMapper.updateById(gtbp);
        //计算调货单总数量
        int quantityTotal = 0;
        List<GoodsTransBillProduct> products = goodsTransBillProductMapper.selectList(new QueryWrapper<GoodsTransBillProduct>().eq("goods_trans_id", gtbd.getGoodsTransBillId()));
        if (products.size() > 0) {
            for (GoodsTransBillProduct g : products) {
                quantityTotal += g.getQuantity();
            }
            gtb.setQuantity(quantityTotal);
        }
        //修改调拨单
        boolean flag = updateById(gtb);
        if (flag) {
            insertOpertaion(gtb, "修改调拨单");
        }
        return flag;
    }

    @Override
    public boolean updateRemark(NewGoodsTransBillDto gtbd, Long uid) {
        //查出调货单
        GoodsTransBill gtb = getOne(new QueryWrapper<GoodsTransBill>().eq("id", gtbd.getGoodsTransBillId()));
        if (ObjectUtil.isEmpty(gtb)) {
            return false;
        }
        gtb.setUpdatedBy(uid);
        gtb.setUpdatedTime(new Date());
        gtb.setRemark(gtbd.getRemark());
        //修改调拨单
        return updateById(gtb);
    }

    private void insertOpertaion(GoodsTransBill goodsTransBill, String remark) {
        GoodsTransBillOperation operation = new GoodsTransBillOperation();
        List<GoodsTransBillOperation> operationList = goodsTransBillOperationService.list(new QueryWrapper<GoodsTransBillOperation>().eq("status", goodsTransBill.getTransStatus()).eq("trans_bill_id", goodsTransBill.getTransStatus()));
        if (operationList == null || operationList.size() == 0) {
            operation.setCreatedBy(goodsTransBill.getCreatedBy());
            operation.setOperator(goodsTransBill.getPromoter());
            operation.setTransBillId(goodsTransBill.getId());
            operation.setStatus(goodsTransBill.getTransStatus());
            operation.setRemark(null == goodsTransBill.getRemark() ? remark : goodsTransBill.getRemark());

            goodsTransBillOperationService.save(operation);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void chgTransStatus(ChgTransStatusDto chgTransStatusDto, Long uid) {
        chgTransStatusDto.setUpdatedBy(uid);
        chgTransStatusDto.setUpdatedTime(new Date());
    /*    GoodsTransBill bill=new GoodsTransBill();
        bill.setId(chgTransStatusDto.getId());*/
        if (chgTransStatusDto.getTransStatus().getValue().equals(TransStatusEunm.TYPE_2.getValue())) {//已审核，入库仓库出货
           /* bill.setTransStatus(TransStatusEunm.TYPE_2.getValue());
              updateById(bill);*/
            auditInOrOut(chgTransStatusDto, 1);
        }
        if (chgTransStatusDto.getTransStatus().getValue().equals(TransStatusEunm.TYPE_3.getValue())) {//已确认申请仓库入库
           /* bill.setTransStatus(TransStatusEunm.TYPE_3.getValue());
            updateById(bill);*/
            auditInOrOut(chgTransStatusDto, 2);
        }
        baseMapper.chgTransStatus(chgTransStatusDto);
    }

    /*申请仓库入库*/
    private void auditInOrOut(ChgTransStatusDto chgTransStatusDto, int flag) {//flag 1 出   2 入
        GoodsTransBill entity = getById(chgTransStatusDto.getId());//调拨单
        //查询ERP仓ID
        Depot depot = depotService.getDepotByCode(GlobalConstant.DepotCode.ERP);
        if (flag == 1
                && ObjectUtil.isNotEmpty(depot)
                && depot.getId().equals(entity.getOutputDepot())) {
            //当出库仓库为ERP仓时调用ERP出库单
            List<GoodsTransBillProductVo> list = goodsTransBillProductMapper.getGoodsTransBillProductByGoodsTransId(entity.getId(), null,new GoodsTransQuery());//获取商品列表
            erpOutDepot(entity.getTransBillSn(), list);
        } else {
            List<GoodsTransBillProductVo> list = goodsTransBillProductMapper.getGoodsTransBillProductByGoodsTransId(entity.getId(), entity.getOutputDepot(),new GoodsTransQuery());//获取商品列表
            //更新仓库库存
            updataStock(list, entity, flag);
        }
        if (flag == 1 && ObjectUtil.isNotEmpty(depot)
                && depot.getId().equals(entity.getInputDepot())) {
            //当入库仓库为ERP仓时调用ERP入库单
            List<GoodsTransBillProductVo> list = goodsTransBillProductMapper.getGoodsTransBillProductByGoodsTransId(entity.getId(), null,new GoodsTransQuery());//获取商品列表
            erpInDepot(entity.getTransBillSn(), list);
        }
    }

    //ERP出库调用
    private void erpOutDepot(String transBillSn, List<GoodsTransBillProductVo> list) {
        OutDepot outDepot = new OutDepot();
        outDepot.setOutdepot(transBillSn);
        outDepot.setDepotid(GlobalConstant.ERP_DEPOT_ID);
        outDepot.setSupplierid(GlobalConstant.ERP_SUPPLIER_ID);
        outDepot.setOuttype("商城调拨");
        outDepot.setSetdate(DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
        outDepot.setComment("调拨单出库");
        List<OutDepotSub> subList = Lists.newArrayList();
        for (GoodsTransBillProductVo gtbpv : list) {
            OutDepotSub outDepotSub = new OutDepotSub();
            outDepotSub.setSku(gtbpv.getProductSn());
            outDepotSub.setNums(gtbpv.getQuantity());
            if (gtbpv.getDiscountPrice() != null) {
                outDepotSub.setS_price(gtbpv.getDiscountPrice().toString());
            }
            outDepotSub.setComment("调拨单出库商品");
            subList.add(outDepotSub);
        }
        outDepot.setOutdepot_sub(subList);
        erpFeign.addOutDepot(outDepot);
    }

    //ERP入库调用
    private void erpInDepot(String transBillSn, List<GoodsTransBillProductVo> list) {
        InDepot inDepot = new InDepot();
        inDepot.setIndepot(transBillSn);
        inDepot.setDepotid(GlobalConstant.ERP_DEPOT_ID);
        inDepot.setSupplierid(GlobalConstant.ERP_SUPPLIER_ID);
        inDepot.setIntype("商城调拨");
        inDepot.setSetdate(DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
        inDepot.setComment("调拨单入库");
        List<InDepotSub> subList = Lists.newArrayList();
        for (GoodsTransBillProductVo gtbpv : list) {
            InDepotSub inDepotSub = new InDepotSub();
            inDepotSub.setSku(gtbpv.getProductSn());
            inDepotSub.setNums(gtbpv.getQuantity());
            if (gtbpv.getDiscountPrice() != null) {
                inDepotSub.setS_price(gtbpv.getDiscountPrice().toString());
            }
            inDepotSub.setComment("调拨单入库商品");
            subList.add(inDepotSub);
        }
        inDepot.setIndepot_sub(subList);
        erpFeign.addInDepot(inDepot);
    }

    private void updataStock(List<GoodsTransBillProductVo> list, GoodsTransBill entity, int flag) {

        //更新仓库库存
        for (GoodsTransBillProductVo vo : list) {
            ProductStockDetails productStock = new ProductStockDetails();
            ProductStockExistQuery query = new ProductStockExistQuery();
            if (flag == 1) {//出库
                query.setDepotId(entity.getOutputDepot());
                productStock.setId(vo.getStockId());
            } else {
                query.setDepotId(entity.getInputDepot());
            }

            query.setGoodsId(vo.getGoodsId());
            query.setProductId(vo.getProductId());
            /*  ProductStockVo stock=productStockMapper.selectProductStock(query);*/
            if (flag == 2) {//如果为入库且仓库中无数据，则执行插入操作,初始化仓库操作。出库不会存在空，所以不尽兴判定
                productStock.setDepotId(entity.getInputDepot());
                productStock.setProductId(vo.getProductId());
                Result<ItemVo> result=itemFeign.findById(vo.getGoodsId());
                if(result.isSuccess()){
                    ItemVo itemVo=result.getData();
                    productStock.setProductName(itemVo.getProductName());
                    productStock.setStockPrice(itemVo.getCostPrice());
                    productStock.setMarkerPrice(itemVo.getMarketPrice());
                    productStock.setProductImg(itemVo.getProductImg());
                    productStock.setGoodsSn(itemVo.getGoodsSn());
                }
                productStock.setStockSn(vo.getStockSn());
                productStock.setStorehouse(vo.getStorehouse());

                productStock.setGoodsId(vo.getGoodsId());
                productStock.setProductSkuDesp(vo.getSpec());
                productStock.setProductSn(vo.getProductSn());
                productStock.setStyleNo(vo.getStyleNo());
            }

            if (flag == 1) {//出库
               /* Integer tt=stock.getEnableStock()-vo.getQuantity();
                Integer t2= stock.getStock()-vo.getQuantity();
                if(tt.intValue()<0||t2.intValue()<0){
                        throw  new BusinessException("出库量不允许大于实际库存或者可用库存");
                }

*/
                //形成一个出库详情单
                outDepot(list, entity);
                productStockDetailsService.removeById(productStock.getId());

            } else {//入库
            /*    int endbalestock=null==stock.getEnableStock()?0:stock.getEnableStock();
                int stock2=null==stock.getEnableStock()?0:stock.getEnableStock();
                productStock.setEnableStock(endbalestock+vo.getQuantity());//增加库存
                productStock.setStock(stock2+vo.getQuantity());*/
                //形成一个入库单详情
                inDepot(list, entity);
                productStockDetailsService.save(productStock);

            }
           /* if(productStock.getStock().intValue()<0){
                throw new BusinessException("库存不允许小于0");
            }*/
           /* if (productStock.getId() == null) {

            } else {

              *//*  ProductStockVo stockcheck=productStockMapper.selectProductStock(query);
                if(stockcheck.getStock().intValue()<0||stockcheck.getEnableStock().intValue()<0){
                    throw  new BusinessException("出库量不允许大于实际库存或者可用库存");
                }*//*
            }
*/
        }
        if (entity.getTransStatus().intValue() == TransStatusEunm.TYPE_3.getValue()) {
            insertOpertaion(entity, "审核调拨单入库");
        } else {
            insertOpertaion(entity, "审核调拨单出库");
        }
    }

    private void inDepot(List<GoodsTransBillProductVo> list, GoodsTransBill entity) {
        List<InDepotBill> billList = inDepotBillService.list(new QueryWrapper<InDepotBill>().eq("bill_sn", entity.getTransBillSn()));
        if (billList.size() == 0) {
            InDepotBillDto dto = new InDepotBillDto();
            dto.setIsFinish(WhetherEnum.YES);
            dto.setBillSn(entity.getTransBillSn());
            dto.setInDepotType(DepotTypeEunm.TYPE_6);
            dto.setInputDepot(entity.getInputDepot());
            dto.setOutputDepot(entity.getOutputDepot());
            List<InDepotBillProductDto> products = Lists.newArrayList();
            for (GoodsTransBillProductVo vo : list) {
                InDepotBillProductDto inDto = new InDepotBillProductDto();
                ItemVo itemVo = itemFeign.findById(vo.getProductId()).getData();
                if (itemVo == null) {
                    try {
                        throw new Exception("商品服务不可用");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                BeanUtils.copyProperties(vo, inDto);
                inDto.setStyleNo(itemVo.getStyleNo());
                inDto.setSpec(itemVo.getProductSkuDesp());
                inDto.setProductSn(inDto.getProductSn());
                inDto.setGoodsSn(itemVo.getGoodsSn());
                products.add(inDto);
            }
            dto.setProducts(products);
            //TODO 需要单独的写一个方法来执行，不在使用之前的可以解决问题
            Long id = inDepotBillService.save(dto, entity.getCreatedBy());
            InDepotBill inDepotBill = new InDepotBill();
            inDepotBill.setIsFinish(WhetherEnum.YES.getValue());
            inDepotBill.setCreatedBy(entity.getCreatedBy());
            inDepotBill.setCreatedTime(new Date());
            inDepotBill.setId(id);
            inDepotBillService.updateById(inDepotBill);
            //   inDepotBillService.saveAndAudit(dto,entity.getCreatedBy());
        }
    }

    private void outDepot(List<GoodsTransBillProductVo> list, GoodsTransBill entity) {
        List<OutDepotBill> billList = outDepotBillService.list(new QueryWrapper<OutDepotBill>().eq("bill_sn", entity.getTransBillSn()));
        if (billList.size() == 0) {
            OutDepotBillDto outDepotBillDto = new OutDepotBillDto();
            outDepotBillDto.setIsFinish(WhetherEnum.YES);
            outDepotBillDto.setBillSn(entity.getTransBillSn());
            outDepotBillDto.setInputDepot(entity.getInputDepot());
            outDepotBillDto.setOutputDepot(entity.getOutputDepot());
            outDepotBillDto.setOutDepotType(DepotTypeEunm.TYPE_6);
            List<OutDepotBillProductDto> billProductDtos = Lists.newArrayList();
            for (GoodsTransBillProductVo vo : list) {
                OutDepotBillProductDto dto = new OutDepotBillProductDto();
                BeanUtils.copyProperties(vo, dto);
                dto.setOutDepotId(entity.getOutputDepot());
                if (null == vo.getStyleNo()) {
                    dto.setStyleNo(vo.getStyleNo());
                }

                billProductDtos.add(dto);
            }
            outDepotBillDto.setProducts(billProductDtos);
            //TODO 需要单独的写一个方法来执行，不在使用之前的可以解决问题
            OutDepotBill outDepotBill = new OutDepotBill();
            long id = outDepotBillService.save(outDepotBillDto, entity.getCreatedBy());
            outDepotBill.setUpdatedBy(entity.getCreatedBy());
            outDepotBill.setUpdatedTime(new Date());
            outDepotBill.setIsFinish(WhetherEnum.YES.getValue());
            outDepotBill.setId(id);
            outDepotBillService.updateById(outDepotBill);
            // outDepotBillService.saveAndAuit(outDepotBillDto,entity.getCreatedBy());
        }
    }


    @Override
    public GoodsTransBillListVo getGoodsTransBillById(long id) {
        return baseMapper.getGoodsTransBillById(id);
    }

    //TODO 调拨单号没添加
    @Override
    public void tranBillGenerate(Long uid) {
        GoodsTransBill goodsTransBill = new GoodsTransBill();
        //获取所有仓库
        List<Depot> depots = depotMapper.selectList(new QueryWrapper<Depot>());
        //根据获取的登录人Id得到登录人的角色
        Result<List<RoleVo>> roleById = sysUserRpcService.getRoleById(Long.valueOf(1));
        List<RoleVo> data = roleById.getData();
        for (RoleVo datum : data) {
            if (datum.getRoleCode().equals("appgly")) {
                for (Depot depot : depots) {
                    if (depot.getDepotName().equals("App仓")) {
                        goodsTransBill.setInputDepot(depot.getId());
                    }
                }
            } else if (datum.getRoleCode().equals("fhbzg")) {
                for (Depot depot : depots) {
                    if (depot.getDepotName().equals("发货部仓")) {
                        goodsTransBill.setInputDepot(depot.getId());
                    }
                }
            }
            goodsTransBill.setPromoter(uid);
            goodsTransBill.setCreatedBy(uid);
            goodsTransBill.setTransStatus(TransStatusEunm.TYPE_1.getValue());
        }
        //获取调拨单中的清单
        GoodsTransBillProduct goodsTransBillProduct = new GoodsTransBillProduct();
        for (Depot depot : depots) {
            if (depot.getDepotName().equals("App仓") && depot.getIsEnable() == 1) {
                List<TransferListVo> list = orderServiceRpc.byDepotId(depot.getId());
                goodsTransBill.setOutputDepot(depot.getId());
                orderServiceRpc.updateOrderStatusS(Math.toIntExact(depot.getId()));
                saveGoodsBill(goodsTransBill, goodsTransBillProduct, list, uid);
            } else if (depot.getDepotName().equals("发货部仓") && depot.getIsEnable() == 1) {
                List<TransferListVo> lists = orderServiceRpc.byDepotId(depot.getId());
                goodsTransBill.setOutputDepot(depot.getId());
                if (lists.size() != 0) {
                    saveGoodsBill(goodsTransBill, goodsTransBillProduct, lists, uid);
                }
                orderServiceRpc.updateOrderStatusS(Math.toIntExact(depot.getId()));
            }
            //外采仓不生成调拨单只改变订单状态
            orderServiceRpc.updateOrderStatusS(0);
        }
    }

    @Override
    public void createBill(BillSaveDto billSaveDto) {
        //TODO 记录下出库的信息

        //初始化调拨单
        Long id = initBill(billSaveDto);
        if (id != null) {
            //商品详情
            List<BillProductDto> dtoList = billSaveDto.getProductIds();
            List<Long> idList=dtoList.stream().map(BillProductDto::getStockId).collect(Collectors.toList());

            Collection<ProductStockDetails> stockDetailsList = productStockDetailsService.listByIds(idList);

           /* List<Long> productList = dtoList.stream().map(BillProductDto::getProductId).collect(Collectors.toList());
            long[] productArray = new long[productList.size()];
            for (int i = 0; i < productList.size(); i++) {
                productArray[i] = productList.get(i);
            }
            //查询ERP仓ID
            Depot depot = depotService.getDepotByCode(GlobalConstant.DepotCode.ERP);
            List<ProductStockDetailsVo> stockVoList = Lists.newArrayList();
            if (ObjectUtil.isNotEmpty(depot)
                    && billSaveDto.getOutDepotId().equals(depot.getId())) {
                //特殊处理 这里针对ERP单独特殊处理
                //逻辑 若为ERP仓则跳过本地仓库查询直接查询商品基本信息封装成库存信息进行调拨单详情生成
                List<ActivityProductVo> productVoList = itemFeign.findActProductVoByIds(productArray).getData();
                for (BillProductDto dto : dtoList) {
                    for (ActivityProductVo apv : productVoList) {
                        if (dto.getProductId().equals(apv.getProductId())) {
                            ProductStockDetailsVo psv = new ProductStockDetailsVo();
                            psv.setGoodsId(apv.getGoodsId());
                            psv.setGoodsName(apv.getGoodsName());
                            psv.setProductId(apv.getProductId());
                            psv.setProductSn(apv.getProductSn());
                            psv.setStock(dto.getStock());
                            psv.setStyleNo(apv.getStyleNo());
                            psv.setProductSkuDesp(apv.getProductSkuDesp());
                            if (ObjectUtil.isNotEmpty(apv.getDiscountPrice())) {
                                psv.setStockPrice(apv.getDiscountPrice().toString());
                            } else {
                                psv.setStockPrice("0");
                            }
                            psv.setStockSn(dto.getStockSn());

                           // psv.setOrderSn(dto.getOrderSn());
                            stockVoList.add(psv);
                        }
                    }
                }
            } else {
                List<ProductStockDetailsVo> stocks = productStockDetailsService.getAllAvaByDepotId(billSaveDto.getOutDepotId());
                for (int i = 0; i < stocks.size(); i++) {
                    ProductStockDetailsVo vo = stocks.get(i);
                    for (long tt : productArray) {
                        if (vo.getProductId().longValue() == tt) {
                            stockVoList.add(vo);
                            break;
                        }
                    }
                }
                //List<ActivityProductVo> productVoList = itemFeign.findActProductVoByIds(productArray).getData();
                //调拨单详情生成。
                // List<BillProductDto> list = Lists.newArrayList();
                for (BillProductDto dto : dtoList) {
                    for (ProductStockVo vo : stockVoList) {
                        if (dto.getProductId().equals(vo.getProductId())) {
                            vo.setStock(dto.getStock());//临时使用
                            vo.setOrderSn(dto.getOrderSn());
                        }
                    }
                }
            }*/
            createBillDetails(id, stockDetailsList, billSaveDto);
            GoodsTransBill entity = new GoodsTransBill();
            entity.setTransStatus(TransStatusEunm.TYPE_1.getValue());

            entity.setCreatedBy(billSaveDto.getUid());
            entity.setId(id);
            entity.setPromoter(billSaveDto.getUid());
            insertOpertaion(entity, "审核调拨申请单");
        }
    }

    @Override
    public GoodsTransBill selectMaxId() {
        GoodsTransBill bill = baseMapper.selectMaxId();
        if (null == bill) {
            bill = new GoodsTransBill();
            bill.setId(1L);
            return bill;
        }
        return baseMapper.selectMaxId();
    }

    @Override
    public String creatTransBill(String prefix) {
        long liveTime = 86400L;
        String dateFmt = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        String key = IdGenTagEnum.DEPOT_TRANS_SN_REDIS.getValue() + dateFmt;
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {//初始设置过期时间
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        String result = DepotUtil.genTransBillSn(prefix, dateFmt, increment + 1);//不从零开始
        return result;
    }

    @Override
    public boolean checkTransBill(GoodsTransBillDto goodsTransBillDto) {
        List<ProductStockVo> stockList = productStockMapper.getAllByDepotId(goodsTransBillDto.getOutputDepot());
        for (ProductStockVo stockVo : stockList) {
            List<GoodsTransBillProductDto> dtoList = goodsTransBillDto.getProducts();
            for (GoodsTransBillProductDto dto : dtoList) {
                if (dto.getProductId().longValue() == stockVo.getProductId().longValue()) {
                    if (dto.getQuantity().intValue() > stockVo.getStock().intValue()) {//如果出库大于库存则进行报错处理
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    public boolean checkTransBillProduct(NewGoodsTransBillDto ngtbd) {
        List<ProductStockVo> stockList = productStockMapper.getAllByDepotId(ngtbd.getOutputDepot());
        for (ProductStockVo stockVo : stockList) {
            if (ngtbd.getProductId().longValue() == stockVo.getProductId().longValue()) {
                if (ngtbd.getQuantity().intValue() > stockVo.getStock().intValue()) {//如果出库大于库存则进行报错处理
                    return true;
                }
            }
        }
        return false;
    }


    private void createBillDetails(Long id, Collection<ProductStockDetails> productVoList, BillSaveDto billSaveDto) {
        List<GoodsTransBillProduct> billProductList = Lists.newArrayList();
        for (ProductStockDetails vo : productVoList) {
            GoodsTransBillProduct entity = new GoodsTransBillProduct();
            entity.setCreatedBy(billSaveDto.getUid());
            entity.setGoodsTransId(id);
            entity.setGoodsId(vo.getGoodsId());
            entity.setProductImg(vo.getProductImg());
            List<BillProductDto> productIds=billSaveDto.getProductIds();
          for(BillProductDto dto:productIds){
              if(dto.getStockId().equals(vo.getId())){
                  entity.setOrderSn(dto.getOrderSn());
                  entity.setOrderType(dto.getOrderType());
                  entity.setFl(dto.getFl());
              }
          }
            entity.setGoodsName(vo.getProductName());
            entity.setProductId(vo.getProductId());
            entity.setProductSn(vo.getProductSn());
            entity.setGoodsSn(vo.getGoodsSn());
            entity.setQuantity(1);
            entity.setStyleNo(vo.getStyleNo());
            entity.setSpec(vo.getProductSkuDesp());
            entity.setStockSn(vo.getStockSn());
            entity.setStockId(vo.getId());
            entity.setStatus(0);
            entity.setDiscountPrice(vo.getStockPrice());
            billProductList.add(entity);
        }
        goodsTransBillProductService.saveBatch(billProductList, ListUtil.SIZE);
    }

    private Long initBill(BillSaveDto billSaveDto) {
        if (null != billSaveDto.getProductIds()) {
            GoodsTransBill goodsTransBill = new GoodsTransBill();
            goodsTransBill.setPromoter(billSaveDto.getUid());
            goodsTransBill.setCreatedBy(billSaveDto.getUid());
            goodsTransBill.setQuantity(billSaveDto.getBillNum());
            goodsTransBill.setInputDepot(billSaveDto.getInDepotId());
            goodsTransBill.setOutputDepot(billSaveDto.getOutDepotId());
            goodsTransBill.setRemark(billSaveDto.getRemark());
            goodsTransBill.setFhId(billSaveDto.getShipperId());
            goodsTransBill.setFhName(billSaveDto.getShipperName());
            goodsTransBill.setTransStatus(TransStatusEunm.TYPE_1.getValue());
            List<BillProductDto> billProductDtos=billSaveDto.getProductIds();
            BigDecimal disCount=new BigDecimal(0);
            try{
                for(BillProductDto dto:billProductDtos) {
                    ItemVo itemVo = itemFeign.findById(dto.getGoodsId()).getData();
                     disCount=disCount.add(itemVo.getDiscountPrice()).setScale(BigDecimal.ROUND_UP);
                    goodsTransBill.setAmount(disCount);
                }
                }catch(Exception e){


            }

            save(goodsTransBill);
            goodsTransBill.setTransBillSn(creatTransBill(SnCodeEnum.TRANSBILLSN.getValue()));
            updateById(goodsTransBill);
            return goodsTransBill.getId();
        } else {
            return null;
        }
    }

    private void saveGoodsBill(GoodsTransBill goodsTransBill, GoodsTransBillProduct goodsTransBillProduct, List<TransferListVo> list, Long userId) {
        Integer num = 0;
        //统计总数量
        for (TransferListVo transferListVo : list) {
            num += transferListVo.getQuantity();
        }
        goodsTransBill.setQuantity(num);
        save(goodsTransBill);
        for (TransferListVo transferListVo : list) {
            goodsTransBillProduct.setGoodsTransId(goodsTransBill.getId());
            goodsTransBillProduct.setGoodsName(transferListVo.getGoodsName());
            goodsTransBillProduct.setSpec(transferListVo.getProductSkuDesp());
            goodsTransBillProduct.setProductId(transferListVo.getProductId());
            goodsTransBillProduct.setProductSn(transferListVo.getProductSn());
            goodsTransBillProduct.setQuantity(transferListVo.getQuantity());
            goodsTransBillProduct.setCreatedBy(userId);
            goodsTransBillProduct.setGoodsId(transferListVo.getGoodsId());
            goodsTransBillProductMapper.insert(goodsTransBillProduct);
        }
        //添加调拨单号
        GoodsTransBill g = new GoodsTransBill();
        String transBillSn = creatTransBill(SnCodeEnum.TRANSBILLSN.getValue());
        g.setId(goodsTransBill.getId());
        g.setTransBillSn(transBillSn);
        updateById(g);
    }
}
